// 粉丝
// follower 粉丝
// following 关注某人

import _ from 'lodash'
import { UserInfo } from './user-info.js'
import { User } from './users.js'
import { createDB } from '../db/index.js'
const db = await createDB('follow', 'object')
await db.read()

const followData = db.chain.get('data')

// 为某用户增加粉丝
const addFollower = async (o, l) => {
    const data = followData.value()
    if(!data[o]) {
        data[o] = { follower: [l] }
    } else {
        if(!data[o].follower) {
            data[o].follower = [l]
        } else {
            data[o].follower.unshift(l)
        }
    }

    await db.write()
}

// 为某用户减少粉丝


// 获取用户详细信息
const getUserInfo = (arr) => {
    let res = []
    arr.forEach(async (id) => {
        const userInfo = await UserInfo.findById(id)
        let user = {}
        if(_.isEmpty(userInfo)) {
            user = await User.findOne({ id, id })
        }
        res.push({
            id: userInfo.id || user.id,
            avatarUrl: userInfo.avatarUrl || '',
            nickname: userInfo.nickname || user.name || '',
            brief: userInfo.brief || ''
        })
    })

    return res
}


export const Follow = {
    // 查询关注列表
    async findById(id) {
        const data = followData.value()
        return data[id] || {}
    },
    // 判断是否在关注列表中
    async checkFollowing(id) {
        const data = followData.value()
        if(!data[id]) return false
        const list = data[id].following
        if(!list || _.indexOf(list, id) < 0) return false
        return true
    },
    // 判断是否在对方粉丝列表
    async checkFollow(id, me) {
        const data = followData.value()
        if(!data[id]) return false
        const list = data[id].follower
        if(!list || _.indexOf(list, me) < 0) return false
        return true
    },
    // 关注某人
    async following(myId, id) {
        const data = followData.value()
        if(!data[myId] || !data[myId].following) {
            data[myId] = { following: [id] }
        } else {
            data[myId].following.push(id)
        }
        await addFollower(id, myId)
        await db.write()        
    },
    // 取消关注
    async unFollowing(myId, id) {
        const data = followData.value()
        if(data[myId] && data[myId].following) {
            _.pull(data[myId].following, id)
        }
        if(data[id] && data[id].follower) {
            _.pull(data[id].follower, myId)
        }
        await db.write()
    },
    // 获取粉丝列表
    async followList(id, offset, type = 0) {
        const data = followData.value()
        const list = type === 0 ? data[id].follower : data[id].following
        const start = offset <= 20 ? 0 : offset - 20
        const sliceRes = _.slice(list, start, offset)        
        const res = getUserInfo(sliceRes)
        return res
    }
}